package com.nineclock.sign.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nineclock.common.entity.PageResult;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.filter.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.sign.dto.SalaryDTO;
import com.nineclock.sign.excel.SalaryExcel;
import com.nineclock.sign.mapper.SalaryMapper;
import com.nineclock.sign.pojo.Salary;
import com.nineclock.sign.service.SalaryService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysCompanyUserFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class SalaryServiceImpl implements SalaryService {

    @Autowired
    private SalaryMapper salaryMapper;

    @Autowired
    private SysCompanyUserFeign companyUserFeign;

    /**
     * 查询员工薪资列表
     *
     * @param month
     * @param keyword
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<SalaryDTO> querySalary(String month, String keyword, Integer page, Integer pageSize) {
        //参数校验
        if (StringUtils.isEmpty(month)) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        PageResult<SalaryDTO> result = new PageResult(0L, 0L, Arrays.asList());

        IPage<Salary> iPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Salary> wrapper = new LambdaQueryWrapper<>();
        //查询出符合关键字的员工ids
        if (!StringUtils.isEmpty(keyword)) {
            List<Long> ids = companyUserFeign.queryByKeyword(keyword).getData();
            if (ids == null) {
                //如果为空，表示没有符合关键字的员工
                return result;
            }
            wrapper.in(Salary::getCompanyUserId, ids);
        }
        wrapper.eq(Salary::getMonth, month);
        wrapper.eq(Salary::getCompanyId, CurrentUserHolder.get().getCompanyId());
        //分页查询
        iPage = salaryMapper.selectPage(iPage, wrapper);
        log.info(Long.toString(iPage.getPages()));
        List<Salary> salaryList = iPage.getRecords();

        if (!CollectionUtils.isEmpty(salaryList)) {
            //属性拷贝并补全信息（姓名、工号、部门、职位）
            List<SalaryDTO> salaryDTOList = BeanHelper.copyWithCollection(salaryList, SalaryDTO.class);
            salaryDTOList = salaryDTOList.stream().map(salaryDTO -> {
                SysCompanyUserDTO companyUserDTO =
                        companyUserFeign.queryCompanyUserById(salaryDTO.getCompanyUserId()).getData();
                salaryDTO.setDepartmentName(companyUserDTO.getDepartmentName());
                salaryDTO.setPost(companyUserDTO.getPost());
                salaryDTO.setUserName(companyUserDTO.getUserName());
                salaryDTO.setWorkNumber(companyUserDTO.getWorkNumber());
                return salaryDTO;
            }).collect(Collectors.toList());
            //封装Page对象
            result = new PageResult(iPage.getTotal(), iPage.getPages(), salaryDTOList);
        }
        return result;
    }


    /**
     * 薪资excel导出
     */
    @Override
    public void excelExport(String month) throws IOException {

        HashMap<String, String> header = new HashMap<>();
        header.put("month",month);
        //获取模板路径
        String templatePath = this.getClass().getResource("/static/SalaryTemplate.xls").getPath();
        log.info(templatePath);
        //获取响应输出流
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();

        //获取excel内容
        List<SalaryDTO> salaryDTOList = this.querySalary(month, null, 1, 100).getRows();
        List<SalaryExcel> salaryExcelList = BeanHelper.copyWithCollection(salaryDTOList, SalaryExcel.class);

        //输出excel
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), SalaryExcel.class)
                .withTemplate(templatePath)
                .build();
        WriteSheet sheet = EasyExcel.writerSheet(0,"薪资列表.xls").build();
        excelWriter.fill(header,sheet);
        excelWriter.fill(salaryExcelList, sheet);
        excelWriter.finish();
    }
}
